const { createProxyMiddleware } = require('http-proxy-middleware');
const { mockServer } = require('../mock/dev');
module.exports = function (app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
      pathRewrite: {'^/api' : ''},
      on:{
        proxyReq: function(proxyReq, req, res) {
          // 请求拦截本地模拟后端接口数据
          // console.log('method:'+req.method,'url:'+req.originalUrl)
          // 当原始请求到发送到服务器前，修改响应内容
          mockServer.api.exclude.forEach(item => {
            if (req.method == item.method && req.originalUrl.startsWith(item.url)) {
              // 将响应设置为JSON内容类型并发送数据
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.write(JSON.stringify(item.data));
              res.end();
            }
          });
          
        }
      }
    })
  );
};